package br.com.mundodaprata.store.data.jpa;

import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import br.com.mundodaprata.store.data.NamedRepository;

public class NamedRepositoryJPA<T>
					extends RepositoryJPA<T>
 					implements NamedRepository<T>{
	
	private String queryName;

	public NamedRepositoryJPA(Class<T> type, 
			                 String queryName) {
		super(type);
		
		this.queryName = queryName;
	}

	@Override
	public T select(String name) {
		EntityManager em = getEntityManager();
		Class<T> type = getType();
		
		TypedQuery<T> query = 
				em.createNamedQuery(queryName, type);
		
		query.setParameter("name", name + "%");
		
		return query.getSingleResult();
	}

	public List<T> all(String name) {
		EntityManager em = getEntityManager();
		Class<T> type = getType();
		
		TypedQuery<T> query = 
				em.createNamedQuery(queryName, type);
		
		query.setParameter("name", name + "%");
		
		try {
			return query.getResultList();
		} catch (NoResultException e) {
			return Collections.emptyList();
		}
	}
}